<template>
  <div>
    <button @click="connectBluetooth">连接蓝牙</button>
    <p v-if="deviceName">已连接设备：{{ deviceName }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      device: null,
      deviceName: '',
    };
  },
  methods: {
    async connectBluetooth() {
      try {
        const device = await navigator.bluetooth.requestDevice({
          filters: [
            { services: ['battery_service'] }, // 你可以换成你设备支持的 service UUID
          ],
          optionalServices: ['device_information'] // 可选服务
        });

        this.device = device;
        this.deviceName = device.name || '未知设备';

        const server = await device.gatt.connect(); // 连接 GATT 服务
        const service = await server.getPrimaryService('battery_service');
        const characteristic = await service.getCharacteristic('battery_level');
        const value = await characteristic.readValue();
        const batteryLevel = value.getUint8(0);

        console.log('电池电量:', batteryLevel + '%');

      } catch (error) {
        console.error('连接蓝牙失败：', error);
      }
    }
  }
}
</script>
